package com.dp.mallchat.common.common.event.listener;

import com.dp.mallchat.common.chat.dao.MessageDao;
import com.dp.mallchat.common.chat.domain.entity.Message;
import com.dp.mallchat.common.chat.domain.entity.Room;
import com.dp.mallchat.common.chat.domain.enums.HotFlagEnum;
import com.dp.mallchat.common.chat.service.cache.RoomCache;
import com.dp.mallchat.common.common.constant.MQConstant;
import com.dp.mallchat.common.common.domain.dto.MsgMessageSendDTO;
import com.dp.mallchat.common.common.event.SendMessageEvent;
import com.dp.mallchat.transaction.service.MQProducter;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Objects;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-30  22:36
 * @Description: 发送消息事件监听
 */
@Component
public class SendMessageEventListener {

    @Autowired
    private MQProducter mqProducter;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private RoomCache roomCache;

    /**
     * TransactionalEventListener
     *      phase：指定目标方法在事务commit之前执行
     *      classes：监听的事件类型
     *      falbackExecution：表明若没有事务的时候，对应的event是否需要执行，默认值为false表示，没事务就不执行了。
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = SendMessageEvent.class, fallbackExecution = true)
    public void sendMessage(SendMessageEvent event){
        //发送mq
        Long msgId = event.getMsgId();
        mqProducter.sendMessage(MQConstant.SEND_MSG_TOPIC, new MsgMessageSendDTO(msgId), msgId);
    }


    @TransactionalEventListener(classes = SendMessageEvent.class, fallbackExecution = true)
    public void handlerMsg(@NotNull SendMessageEvent event) {
        Message message = messageDao.getById(event.getMsgId());
        Room room = roomCache.get(message.getRoomId());
        if (isHotRoom(room)) {
//            openAIService.chat(message);
        }
    }

    public boolean isHotRoom(Room room) {
        return Objects.equals(HotFlagEnum.YES.getType(), room.getHotFlag());
    }

    /**
     * 给用户微信推送艾特好友的消息通知
     * （这个没开启，微信不让推）
     */
    @TransactionalEventListener(classes = SendMessageEvent.class, fallbackExecution = true)
    public void publishChatToWechat(@NotNull SendMessageEvent event) {
        Message message = messageDao.getById(event.getMsgId());
        if (Objects.nonNull(message.getExtra().getAtUidList())) {
//            weChatMsgOperationService.publishChatMsgToWeChatUser(message.getFromUid(), message.getExtra().getAtUidList(),
//                    message.getContent());
        }
    }

}
